#pragma once
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

#define LINE_SIZE 1024
#define FLUSH_LINE 2
#define FLUSH_FULL 4
#define FLUSH_NOW 1

struct myFILE{
  int flags;
  int fileno;
  int cache[LINE_SIZE];
  int cap;
  int pos;
  
};

myFILE* my_fopen(const char* path, const char* sflag)
{
  int flag = 0;
  mode_t mode = 0666;
  int iscreat = 0;
  if(strcmp(sflag, "r") == 0)
  {
    flag = (O_RDONLY);
    iscreat = 1;
  }
  else if(strcmp(sflag, "w") == 0)
  {
    flag = (O_WRONLY | O_CREAT | O_TRUNC);
    iscreat = 1;
  }
  else if(strcmp(sflag, "a") == 0)
  {
    flag = (O_WRONLY | O_CREAT | O_APPEND);
    iscreat = 1;
  }
  else{}

  int fd = 0;
  if(iscreat)
  {
    fd = open(path, flag, mode);
  }
  else{
    fd = open(path, flag);
  }

  if(fd < 0)
  {
    return NULL;
  }

  myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
  if(fp == NULL) return NULL;

  fp->fileno = fd;
  fp->flags = FLUSH_LINE;
  fp->cap = LINE_SIZE;
  fp->pos = 0;


  return fp;

}

size_t my_write(myFILE* fp, const char* data, int len)
{
  //write(fp->fileno, data, len);
  //拷贝
  
  memcpy(fp->cache+fp->pos, data, len);
  fp->pos += len;

  if((fp->flags & FLUSH_LINE) && fp->cache[fp->pos - 1] == '\n')
  {
    write(fp->fileno, fp->cache, fp->pos);
    fp->pos = 0;
  }

  return len;
}

void my_fflush(myFILE* fp)
{
  
    write(fp->fileno, fp->cache, fp->pos);
    fp->pos = 0;
}

void my_fclose(myFILE* fp)
{
  //my_fflush();
  
  close(fp->fileno);
  free(fp);
}

 // myFILE *fp = my_fopen();
 // my_fclose(fp);

 // my_fwrite(fp);
